//
//  ArticlesViewController.m
//  chanyou
//
//  Created by 高爽 on 15-1-4.
//  Copyright (c) 2015年 wanli. All rights reserved.
//

#import "ArticlesViewController.h"
#import "ArticlesTableViewCell.h"
#import "ArticlesModel.h"
#import "ConnectModel.h"
#import "ArtDetailViewController.h"
#import "UIImageView+WebCache.h"

#import "UIScrollView+MJRefresh.h"

#import "Masonry.h"


#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface ArticlesViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger page;
}

@end

@implementation ArticlesViewController


- (void)dealloc
{
    [_table release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        page = 1;
    }return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // self.view.backgroundColor = [UIColor colorWithRed:231/255.0 green:231/255.0 blue:231/255.0 alpha:1.0];
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110) style:UITableViewStylePlain];
    _table.dataSource = self;
    _table.delegate = self;
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_table registerClass:[ArticlesTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:_table];
    [_table release];
    
    [self jsonParser:@"http://chanyouji.com/api/articles.json" test:@""];
    
    [self.table addHeaderWithTarget:self action:@selector(reloadAction)];
    [self.table addFooterWithTarget:self action:@selector(addAction)];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticlesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    // 去掉点击出现的灰色界面
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ArticlesModel *model = [_array objectAtIndex:indexPath.row];
    
    // NSLog(@"titleLabel = %@", model.sectionTitle);
    [cell.titleLabel setText:model.sectionTitle];
    [cell.nameLabel setText:model.name];
    
    // picture
    NSString *pic = model.image_url;
//    [cell.imv imageWithUrl:pic placeHolder:nil];
    [cell.imv sd_setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_HEIGHT / 3 + 10;
    // return (SCREEN_WIDTH - 20) * 0.618;
}

// 解析
- (void)jsonParser:(NSString *)path test:(NSString *)test
{
    [ConnectModel connectModelWithUrl:path parmaters:nil finished:^(NSData *data) {
        // 刷新的时候用到
        if ([test isEqualToString:@"ok"]) {
            [_array removeAllObjects];
        }
        
        NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        for (int i = 0; i < [arr count]; i++) {
            NSMutableDictionary *dic = [arr objectAtIndex:i];
            
            ArticlesModel *model = [[[ArticlesModel alloc] init] autorelease];
            model.image_url = [dic objectForKey:@"image_url"];
            model.name = [dic objectForKey:@"name"];
            model.sectionTitle = [dic objectForKey:@"title"];
            //            NSString *sId = [NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]];
            NSNumber *num = [dic objectForKey:@"id"];
            
            model.sectionId = [num intValue];
            // model.sectionId = sId;
            
            [_array addObject:model];
            [_table reloadData];
        }
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArtDetailViewController *detail = [[[ArtDetailViewController alloc] init] autorelease];
    ArticlesModel *model = [_array objectAtIndex:indexPath.row];
    detail.detailId = model.sectionId;
    detail.articles = model;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)reloadAction
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self jsonParser:@"http://chanyouji.com/api/articles.json" test:@"ok"];
        [self.table headerEndRefreshing];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    });
    [self.table reloadData];

}
- (void)addAction
{
    page++;
    NSString *path = [NSString stringWithFormat:@"http://chanyouji.com/api/articles.json?page=%ld", (long)page];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self jsonParser:path test:@""];
        [self.table footerEndRefreshing];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    });


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
